package com.hmk.blogboot.web;


import com.hmk.blogboot.po.Comment;
import com.hmk.blogboot.po.User;
import com.hmk.blogboot.service.BlogService;
import com.hmk.blogboot.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {

    //自动注入commentService接口
    @Autowired
    private CommentService commentService;
    //自动注入blogService
    @Autowired
    private BlogService blogService;
    //从配置文件中获取avatar 首图地址
    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{blogId}")
    public String comment(@PathVariable Long blogId, Model model){
        //commentService接口调用
        model.addAttribute("comments",commentService.listCommentByBlogId(blogId));
        return "blog :: commentList";
    }



    @PostMapping("/comments")
    public String post(Comment comment , HttpSession session){
        //获取BlogId
        Long blogId = comment.getBlog().getId();
        //根据blogId进行查询到的blog对象设置到comment对象
        comment.setBlog(blogService.getBlog(blogId));
        //通过session获取当前登录的用户的信息
        User user = (User)session.getAttribute("user");
        //如果用户登录
        if(user!=null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        }else{
            comment.setAvatar(avatar);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/" + blogId;
    }

}
